package com.ccl.iot;import com.ccl.iot.IOTInfoMonitor.IOTInfoListener;
import com.ccl.iot.object.IOTInfoWithValue;

public class IOTInfoFilter  {
	private String iPrefix = null;
	private IOTInfoSynchro iInfoSynchro = null;
	private IOTMonitor<IOTInfoListener> iExInfoListener = new IOTMonitor<IOTInfoListener>();
	
	IOTInfoFilter(String aPrefix, IOTInfoSynchro aInfoSynchro){
		iPrefix = aPrefix;
		iInfoSynchro = aInfoSynchro;
	}
	
	public String getPrefix(){
		return iPrefix;
	}
	
	protected boolean addInfoListener(IOTInfoListener aInfoListener){
		if (iExInfoListener.addMonitorListener(aInfoListener)){
			if (iExInfoListener.getMonitorListenerCount(iExInfoListener) == 1){
				if (iPrefix != null && iInfoSynchro != null){
					iInfoSynchro.addInfoListener(iInfoListener);
				}
			}
			
			return true;
		}
		
		return false;
	}
	
	protected boolean removeInfoListener(IOTInfoListener aInfoListener){
		if (iExInfoListener.removeMonitorListener(aInfoListener)){
			if (iExInfoListener.isMonitoring(iExInfoListener) == false){
				if (iPrefix != null && iInfoSynchro != null){
					iInfoSynchro.removeInfoListener(iInfoListener);
				}
			}
		}
		
		return false;
	}
	
	private IOTInfoListener iInfoListener = new IOTInfoListener(){
		private boolean isUsfulInfo(String aName){
			return aName != null && aName.startsWith(iPrefix);
		}
		
		@Override
		public void onNewInfo(IOTInfoWithValue aInfo) {
			if (iExInfoListener != null && aInfo != null && isUsfulInfo(aInfo.getName())){
				int tIndex = 0;
				IOTInfoListener tListener;
				
				while((tListener = iExInfoListener.getMonitorListener(tIndex++)) != null){
					tListener.onNewInfo(aInfo);
				}
			}
		}

		@Override
		public void onInfoChanged(IOTInfoWithValue aInfo) {
			if (iExInfoListener != null && aInfo != null && isUsfulInfo(aInfo.getName())){
				int tIndex = 0;
				IOTInfoListener tListener;
				
				while((tListener = iExInfoListener.getMonitorListener(tIndex++)) != null){
					tListener.onInfoChanged(aInfo);
				}
			}
		}

		@Override
		public void onInfoRemoved(IOTInfoWithValue aInfo) {
			if (iExInfoListener != null && aInfo != null && isUsfulInfo(aInfo.getName())){
				int tIndex = 0;
				IOTInfoListener tListener;
				
				while((tListener = iExInfoListener.getMonitorListener(tIndex++)) != null){
					tListener.onInfoRemoved(aInfo);
				}
			}
		}
	};
	
	protected String getInfoValue(String aName){
		if (aName != null && iPrefix != null && iInfoSynchro != null){
			return iInfoSynchro.getInfoValue(iPrefix + aName);
		}
		
		return null;
	}
	
	protected boolean setInfoValue(String aName, String aValue){
		if (aName != null && iPrefix != null && iInfoSynchro != null){
			return iInfoSynchro.setInfoValue(iPrefix + aName, aValue);
		}
		
		return false;
	}
	
	protected boolean removeInfo(String aName){
		if (aName != null && iPrefix != null && iInfoSynchro != null){
			return iInfoSynchro.removeInfo(iPrefix + aName);
		}
		
		return false;
	}
}
